<?php
namespace app\index\controller;
use think\Request;
class Upload {
    static private $UploadDir_=ROOT_PATH . "public". DS  ."uploads";
    static private $SetDirname='uploads';
    static private $Request_;
    /**
     *图片上传后的路径。
     * @var array  $path
     */
    static public $path=[];
    static private $Verification_=[
        "size"=>5*1024*1024,//5M
        'ext'=>'jpg,png,gif,image'
    ];
    /**
     * 自动注入。不用管直接用就可以了
     * @param Request $Request
     */
    public function __construct(Request $Request) {
        self::$Request_=$Request;
    }
    /**
     * 上传文件
     * @param string $name  上传的key名称
     */
    public function Uploads_(string $name){
        $files =self::$Request_->file($name);
        if(is_object($files)){ #是对象说明是单个文件
            return  $this->SingleImge($files);
        }elseif (is_array($files)){
            return $this->ManyImage($files);
        }else{
            return false;
//            echo "未上传文件";
//            exit(json_encode([
//                "code"=>11111,
//                "msg"=>$objcet->getError(),
//                "data"=>[],
//            ]));
        }
    }
    /**
     * 解决
     * 如图片上传压缩
     * iOS上传图片倾斜问题
     */
    public function DisposeImge(){
//        print_r(self::$path);
        
    }

    private function SingleImge(\think\File $objcet){
        $info=$objcet->validate(self::$Verification_)->move(self::$UploadDir_);
        if($info){
            self::$path[]=self::$UploadDir_.DS.$info->getSaveName();
            return self::$SetDirname.DS.$info->getSaveName();
        }else{
            exit(json_encode([
                "code"=>11111,
                "msg"=>$objcet->getError(),
                "data"=>[],
            ]));
        }
    }
    private function ManyImage(array $array){
        $name=[];
        foreach($array as $objcet){
           $name[]= $this->SingleImge($objcet);
        }
        return $name;
    }

    /**
     * 设置要上传的目录
     * @param type $dir
     */
    public function SetUploadDir(string $dir=''){
        if($dir == ''){
            return $this;
        }
        $Dir =realpath(ROOT_PATH . "public". DS  .$dir);
        if($Dir){
            self::$UploadDir_=$Dir;
        }else{
            mkdir(ROOT_PATH . "public". DS  .$dir ,0777);
            $Dir=realpath(ROOT_PATH . "public". DS  .$dir);
            if(! $Dir){
                exit("不是规范的dir");
            }
        }
        self::$SetDirname=DS.$dir;
        return $this;
    }
    /**
     * 设置验证规则
     * @param array $Verification 规则
     */
    public function SetVerification($Verification=[]){
        if(! empty($Verification) && is_array($Verification)){
            self::$Verification_=$Verification;
        }
        return $this;
    }
}
